package com.pansky.crm.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pansky.crm.common.mybatisplus.QueryWapperUtils;
import com.pansky.crm.common.mybatisplus.ResultPageDto;
import com.pansky.crm.common.mybatisplus.SuperServiceImpl;
import com.pansky.crm.entity.Department;
import com.pansky.crm.entity.Employee;
import com.pansky.crm.entity.ImageInfo;
import com.pansky.crm.entity.bo.page.ImagePageBo;
import com.pansky.crm.entity.vo.EmployeeVo;
import com.pansky.crm.mapper.mysql.ImageMapper;
import com.pansky.crm.service.ImageService;
import com.pansky.crm.util.BeanUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Collectors;

/**
 * @author ：zhouzhiyong
 * @date ：Created in 2021/3/9 10:46
 * @description：图片管理服务
 */
@Service
@DS("mysqlDb")
public class ImageServiceImpl extends SuperServiceImpl<ImageMapper, ImageInfo> implements ImageService {

    @Override
    public ResultPageDto queryByPage(ImagePageBo imagePageBo) {
        IPage<ImageInfo> page = new Page<>(imagePageBo.getPage(), imagePageBo.getLimit());
        QueryWrapper<ImageInfo> queryWrapper = QueryWapperUtils.queryToWrapper(imagePageBo, ImageInfo.class);
        queryWrapper.orderByDesc("id");
        IPage<ImageInfo> dbResult = page(page, queryWrapper);
        //业务数据
        return defaultTransformPageData(dbResult,
                transform -> dbResult.getRecords().stream().map(imageInfo -> {
                    return BeanUtil.copy(imageInfo, ImageInfo.class);
                }).collect(Collectors.toList()));
    }

    @Override
    public Boolean removeImage(HttpServletRequest request, Integer imageId) {
        ImageInfo imageInfo = getById(imageId);
        String imageUrl = imageInfo.getImageUrl();
        String substring = imageUrl.substring(imageUrl.lastIndexOf("/upload"));
        File file = null;
        try {
            file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "static" + substring);
            if (file.exists()) {
                if (file.delete()) {
                    return removeById(imageId);
                } else {
                    return true;
                }
            } else {
                return false;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        }



    }

}
